//
//  RNIOSExportJsToReact.m
//  xmgjAppFront
//
//  Created by 汪滔 on 2020/7/1.
//

#import <Foundation/Foundation.h>
#import "MapModule.h"
#import <React/RCTLog.h>
#import "GJUtil.h"
#import <YYModel/YYModel.h>
@interface MapModule ()
@property (nonatomic, assign)__block BOOL isContinue;
@end
@implementation MapModule
RCTPromiseResolveBlock locationResolveBlock;
RCTPromiseRejectBlock locationReject;
RCT_EXPORT_MODULE();

RCT_REMAP_METHOD(getCurrentPosition,resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
  locationResolveBlock = resolve;
  locationReject = reject;
  dispatch_async(dispatch_get_main_queue(), ^{
     [self getLoaction];
   });
}

RCT_EXPORT_METHOD(registerSuggestionListener){
  
}
RCT_EXPORT_METHOD(unregisterSuggestionListener){
  
}

RCT_EXPORT_METHOD(suggestionSearch:(NSDictionary *)params callback:(RCTResponseSenderBlock) callback){
  if (self.isContinue) {
    return;
  }
  self.isContinue = YES;
  NSString *keyword = [params[@"keyword"] gj_hasValue]?params[@"keyword"]:@"";
  NSString *city = [params[@"city"] gj_hasValue] ? params[@"city"] :@"";
  dispatch_async(dispatch_get_main_queue(), ^{
    if (![keyword gj_hasValue]) {
//      callback(@[]);
      self.isContinue = NO;
      return;
    }
    //poi 检索
    [[GJLocationUtil shareInstance] searchPOIWithKeyWords:keyword city:city complete:^(NSArray * _Nonnull resultArray) {
      if (resultArray.count > 0) {
        callback(@[[resultArray jsonStringEncoded]]);
      }else{
//        callback(@[]);
      }
      self.isContinue = NO;
    }];
  });
}

/// 定位
- (void)getLoaction{
  [[GJLocationUtil shareInstance] getLocationWithCommplete:^(CLLocationCoordinate2D coordinate, NSDictionary * _Nonnull addressDic, NSError * _Nonnull error) {
    [[GJLocationUtil shareInstance] stopSerialLocation];
    if (error == nil) {
      locationResolveBlock(addressDic);
    }else{
      if (![GJUtil hasLocationAuthorization]) {
        [UIAlertController showAlertInViewController:[UIApplication sharedApplication].keyWindow.rootViewController withTitle:@"请允许访问位置信息" message:@"我们将获取您的位置信息，用于展示你的当前地址" cancelButtonTitle:@"取消" destructiveButtonTitle:@"同意" otherButtonTitles:nil tapBlock:^(UIAlertController * _Nonnull controller, UIAlertAction * _Nonnull action, NSInteger buttonIndex) {
              if (buttonIndex == 1) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
              }
        }];
        return;
      }
      locationReject(@"000000",@"获取定位失败",error);
    }
  }];
}
@end
